//
//  HJBleInfoViewController.m
//  bleDemo
//
//  Created by wurz on 15/4/13.
//  Copyright (c) 2015年 wurz. All rights reserved.
//

#import "HJBleInfoViewController.h"

@interface HJBleInfoViewController ()
{
    UITableView *_tableView;
    NSMutableArray *_tableData;
    NSMutableDictionary *_rssiDict;
    NSMutableArray *_tableHeader;
    
    BluetoothLe *_ble;
    NSTimer *_timer;
}

@end

@implementation HJBleInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    _tableHeader = [NSMutableArray array];
    [_tableHeader addObject:@""]; //无标题
    [_tableHeader addObject:@""]; //无标题
    
    _tableData = [[NSMutableArray alloc] init];
    
    NSArray *group1 = @[@{@"Name":_scanData.peripheral.name},@{@"UUID":_scanData.peripheral.identifier.UUIDString}];
    [_tableData addObject:group1];
    
    _rssiDict = [[NSMutableDictionary alloc] init];
    [_rssiDict setObject:[NSString stringWithFormat:@"%@dB",_scanData.RSSI] forKey:@"RSSI"];
    
    group1 = @[_rssiDict,@{@"Manufacturer Data":[NSString hexToString:_scanData.advertisementData[@"kCBAdvDataManufacturerData"] space:YES]}];
    [_tableData addObject:group1];
    
    for (CBService *service in _scanData.peripheral.services) {
        if ([service.UUID.UUIDString isEqualToString:@"180A"]) {
            continue;
        }
        [_tableHeader addObject:[NSString stringWithFormat:@"service:%@",service.UUID.UUIDString]];
        NSMutableArray *array = [NSMutableArray array];
        for (CBCharacteristic *c in service.characteristics) {
            NSString *property = @"";
            if (c.properties & CBCharacteristicPropertyRead) {
                property = [property stringByAppendingString:@"可读,"];
            }
            if (c.properties & CBCharacteristicPropertyWrite) {
                property = [property stringByAppendingString:@"可写,"];
            }
            if (c.properties & CBCharacteristicPropertyNotify) {
                property = [property stringByAppendingString:@"通知,"];
            }
            [array addObject:@{property:c.UUID.UUIDString}];
        }
        [_tableData addObject:array];
    }
    
    self.navigationItem.title = _scanData.peripheral.name;
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backHome)];
    
    //解决定义按钮与边框距离过大问题
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    spaceItem.width = -12;
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarItem];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"蓝牙" style:UIBarButtonItemStylePlain target:self action:@selector(backHome)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"操作" style:UIBarButtonItemStylePlain target:self action:@selector(toHandleView)];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height) style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(readRssiTimer:) userInfo:nil repeats:YES];
    
    _ble = [BluetoothLe shareBandConnectionWithDelegate:self];
    _ble.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- timer
-(void)readRssiTimer:(NSTimer *)timer
{
    [_ble readRssi:_scanData.peripheral];
}

#pragma mark -- 返回
-(void)backHome
{
    [_ble disconnect:_scanData.peripheral];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark -- 进入操作界面
-(void)toHandleView
{
    BleViewController *bleView = [[BleViewController alloc] init];
    bleView.peripheral = _scanData.peripheral;
    bleView.delegate = self;
    [self.navigationController pushViewController:bleView animated:YES];
}


#pragma mark -- UITableViewDataSource
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return _tableHeader[section];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _tableData.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = _tableData[section];
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentify];
        [cell.detailTextLabel setTextColor:[UIColor grayColor]];
    }
    
    NSDictionary *dict = _tableData[indexPath.section][indexPath.row];
    if ([dict.allKeys[0] isEqualToString:@"UUID"]) {
        cell.textLabel.numberOfLines = 2;
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.detailTextLabel.text = dict.allKeys[0];
    cell.textLabel.text = dict.allValues[0];
    
    return cell;
}

#pragma mark -- UITableViewDelegete
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = _tableData[indexPath.section][indexPath.row];
    if ([dict.allKeys[0] isEqualToString:@"UUID"]) {
        return 60;
    }
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark -- BluetoothLeDegelete
-(void)ble:(BluetoothLe *)ble didLocalState:(BleLocalState)state{
    if (state != BleLocalStatePowerOn) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        if ([self.delegate respondsToSelector:@selector(hjBleViewShowMessage:)]) {
            [self.delegate hjBleViewShowMessage:@"蓝牙已关闭"];
        }
    }
}

-(void)ble:(BluetoothLe *)ble didDisconnect:(CBPeripheral *)peripheral
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    if ([self.delegate respondsToSelector:@selector(hjBleViewShowMessage:)]) {
        [self.delegate hjBleViewShowMessage:@"蓝牙已断开"];
    }
}

-(void)ble:(BluetoothLe *)ble didUpdateRssi:(CBPeripheral *)peripheral rssi:(NSNumber *)rssi
{
    //更新rssi
    _rssiDict[@"RSSI"] = [NSString stringWithFormat:@"%@dB",rssi];
    [_tableView reloadData];
}

#pragma mark -- BleViewControllerDelegate
-(void)handleBleViewShowMessage:(NSString *)message
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    if ([self.delegate respondsToSelector:@selector(hjBleViewShowMessage:)]) {
        [self.delegate hjBleViewShowMessage:message];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
